#include "qlogmgr.h"

QLogMgr::QLogMgr()
{

}

QLogMgr::~QLogMgr()
{

}

void QLogMgr::setUpDetailLogging()
{
    // 1. 创建详细的布局模式
    auto* pLayout = new Log4Qt::PatternLayout();
    pLayout->setConversionPattern("%d{yyyy-MM-dd HH:mm:ss.zzz} [%-5p] %m%n");
    pLayout->activateOptions();

    // 2.创建文件输出
    QString exeDir = QCoreApplication::applicationDirPath();
    QString strFilePath = QDir(exeDir).filePath("application.log");
    auto* pFileAppender = new Log4Qt::FileAppender(pLayout,strFilePath,true);
    pFileAppender->activateOptions();

    // 3.根据记录器绑定 Appender
    Log4Qt::Logger::rootLogger()->addAppender(pFileAppender);
    Log4Qt::Logger::rootLogger()->setLevel(Log4Qt::Level::INFO_INT);

}


void QLogMgr::demoLogging()
{
    // 获取不同类别的记录器
    Log4Qt::Logger* rootLogger = Log4Qt::Logger::rootLogger();
    Log4Qt::Logger* networkLogger = Log4Qt::Logger::logger("Network");
    Log4Qt::Logger* databaseLogger = Log4Qt::Logger::logger("Database");
    Log4Qt::Logger* businessLogger = Log4Qt::Logger::logger("Business");

    // 输出不同级别的日志
    rootLogger->debug("Application started");
    rootLogger->info("Initialization completed");

    // 网络相关日志
    networkLogger->debug("Connecting to server: 192.168.1.100:8080");
    networkLogger->info("HTTP GET request sent to /api/data");
    networkLogger->warn("Network latency detected: 150ms");
    networkLogger->error("Connection timeout after 30 seconds");

    // 数据库相关日志
    databaseLogger->debug("Executing SQL: SELECT * FROM users WHERE id = ?");
    databaseLogger->info("Database connection established successfully");
    databaseLogger->error("SQL execution failed: Table 'users' doesn't exist");

    // 业务逻辑日志
    businessLogger->trace("Entering user authentication process");
    businessLogger->debug("User credentials validated");
    businessLogger->info("User login successful: john_doe");
    businessLogger->fatal("Critical business rule violation detected");

    // 带参数的日志
    int userId = 12345;
    QString userName = "John Doe";
    double processingTime = 2.345;

    rootLogger->info("User processed: ID=%1, Name=%2, Time=%3ms",
                     userId, userName, processingTime);

    // 异常日志
    try {
        throw std::runtime_error("Simulated exception for logging");
    } catch (const std::exception& e) {
        rootLogger->error("Exception caught: %1", QString::fromLocal8Bit(e.what()));
    }
}


void QLogMgr::demoMultiThreadLogging()
{
    Log4Qt::Logger* mainLogger = Log4Qt::Logger::logger("Main");
    mainLogger->info("Starting multi-thread logging demo");

    WorkerThread threads[3];

    for (int i = 0; i < 3; ++i)
    {
        threads[i].start();
    }

    for (int i = 0; i < 3; ++i)
    {
        threads[i].wait();
    }

    mainLogger->info("All worker threads completed");
}


void QLogMgr::setupAdvancedLogging()
{
    // 1. 创建不同详细程度的布局
    auto* detailedLayout = new Log4Qt::PatternLayout();
    detailedLayout->setConversionPattern("%d{ISO8601} [%-5p] [%t] %c{2} %F:%L - %m%n");
    detailedLayout->activateOptions();

    auto* simpleLayout = new Log4Qt::PatternLayout();
    simpleLayout->setConversionPattern("[%-5p] %m%n");
    simpleLayout->activateOptions();

    // 2. 滚动文件输出 - 按大小和日期滚动
    auto* rollingFileAppender = new Log4Qt::RollingFileAppender();
    rollingFileAppender->setLayout(detailedLayout);
    rollingFileAppender->setFile("logs/app.log");
    QString str = QString("%1").arg(10 * 1024 * 1024);
    rollingFileAppender->setMaxFileSize(str); // 10MB
    rollingFileAppender->setMaxBackupIndex(5);
    rollingFileAppender->setAppendFile(true);
    rollingFileAppender->activateOptions();

    // 3. 错误日志文件 - 只记录 ERROR 和 FATAL
    auto* errorFileAppender = new Log4Qt::FileAppender(detailedLayout, "logs/error.log", true);

    // 添加级别过滤器
    auto* errorFilter = new Log4Qt::LevelRangeFilter();
    errorFilter->setAcceptOnMatch(true);
    errorFilter->setLevelMin(Log4Qt::Level::ERROR_INT);
    errorFileAppender->addFilter(errorFilter);
    errorFileAppender->activateOptions();

    // 4. 控制台输出 - 简化格式
    auto* consoleAppender = new Log4Qt::ConsoleAppender(simpleLayout);
    consoleAppender->activateOptions();


    // 设置特定记录器的级别
    Log4Qt::Logger::logger("Network")->setLevel(Log4Qt::Level::INFO_INT);
    Log4Qt::Logger::logger("Database")->setLevel(Log4Qt::Level::WARN_INT);
}



